<template>
    <div class="wh-100% select-none">
        <n-card class="w-300px profile-card">
            <template #header>
                <div class="flex items-center gap-10px">
                    <span class="font-size-16px">个人信息</span>
                </div>
            </template>
            <template #header-extra>
                <n-button
                    text
                    class="edit-btn hidden"
                    :focusable="false"
                    @click="userFormvisible = true"
                >
                    <n-icon :size="18">
                        <Create />
                    </n-icon>
                </n-button>
            </template>
            <div class="w-full flex flex-col items-center gap-20px">
                <n-upload
                    class="wh-100px cursor-pointer relative"
                    :show-file-list="false"
                    @change="handleAvatarUpload"
                >
                    <n-avatar
                        round
                        class="absolute"
                        v-if="userInfo.avatar"
                        :src="`http://8.138.113.118/avator/${userInfo.avatar}`"
                        :size="100"
                    />
                    <n-icon
                        v-else
                        class="absolute"
                        :component="PersonCircle"
                        :size="100"
                    />
                    <div
                        class="flex-center absolute wh-100px bg-#f5f5f5 rounded-full opacity-0 hover:opacity-100 ease duration-200"
                    >
                        <n-icon :component="CloudUpload" :size="48" />
                    </div>
                </n-upload>
                <div class="w-full flex-center flex-col">
                    <div class="font-size-20px font-bold">
                        {{ userInfo.username }}
                    </div>
                    <n-tag :type="`primary`">{{
                        userInfo.role === "admin"
                            ? "管理员"
                            : userInfo.role === "customer"
                            ? "客户"
                            : "员工"
                    }}</n-tag>
                </div>
            </div>
            <n-list>
                <n-list-item>
                    <n-thing
                        title="账号"
                        :title-extra="userInfo.account"
                    ></n-thing>
                </n-list-item>
                <div v-if="userInfo.role === 'customer'">
                    <n-list-item>
                        <n-thing
                            title="手机号"
                            :title-extra="(userInfo as Customer).phone"
                        ></n-thing>
                    </n-list-item>
                    <n-list-item>
                        <n-thing title="公司名称">
                            <template #description>
                                <span>季伯市季伯区季伯有限公司</span>
                            </template>
                        </n-thing>
                    </n-list-item>
                </div>
                <n-list-item>
                    <n-thing
                        title="注册时间"
                        :title-extra="new Date().toLocaleDateString()"
                    ></n-thing>
                </n-list-item>
            </n-list>
        </n-card>
        <n-drawer v-model:show="userFormvisible" :width="360" placement="right">
            <n-drawer-content>
                <template #header> 编辑个人信息 </template>
                <UserForm
                    :role="userInfo.role"
                    :model="'update'"
                    :is-user="true"
                    :data="userInfo"
                    @submit:data="handleUpdateUser"
                    @update:password="handleUpdateUser"
                />
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { getStore, resetStores } from "@/store";
import { Create, CloudUpload, PersonCircle } from "@vicons/ionicons5";

import { cloneDeep } from "lodash";

import type { UploadFileInfo } from "naive-ui";
import type { User, Customer } from "@/service/api/types/user";
import { updateUser, updateUserAvatar } from "@/service/api/modules/user";

import UserForm from "@/components/user-form/index.vue";

const router = useRouter();
const userStore = getStore("user");
const userInfo = ref<User | Customer>(cloneDeep(userStore.getUserInfo));

const userFormvisible = ref(false);

// 更新用户信息 --> 更改密码 | 更改用户信息
const handleUpdateUser = async (data: User | Customer | string) => {
    try {
        // 判断是修改密码还是修改用户信息
        const model = typeof data === "string" ? "password" : "data";
        if (typeof data === "string") {
            data = { ...userInfo.value, password: data };
        }
        const newUser = await updateUser(data);

        if (model === "password") {
            window.NDialog.success({
                title: "修改成功",
                content: "修改密码成功, 请重新登陆",
                closable: false,
                maskClosable: false,
                positiveText: "重新登陆",
                onPositiveClick: () => {
                    resetStores();
                    localStorage.clear();
                    router.push({ name: "login" });
                },
            });
        } else {
            userStore.setUserInfo(newUser);
            userFormvisible.value = false;
            userInfo.value = newUser;
            window.NMessage.success("修改成功");
        }
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleAvatarUpload = async (options: { file: UploadFileInfo }) => {
    const { file } = options;
    const { size, type } = file.file!;
    if (size > 1024 * 1024 * 2) {
        window.NMessage.error("图片大小不能超过2M");
        return;
    }
    if (!["image/jpeg", "image/png", "image/webp"].includes(type)) {
        window.NMessage.error("图片格式必须为 jpeg, png, webp");
        return;
    }
    const formdata = new FormData();
    formdata.append("id", userInfo.value.id!);
    formdata.append("image", file.file!);
    try {
        const url = await updateUserAvatar(formdata);
        userInfo.value.avatar = url;
        window.NMessage.success("上传成功");
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};
</script>

<style scoped>
.profile-card:hover .edit-btn {
    display: block;
}
</style>
